<template>
  <div class="room-reserve-container">
    <div class="room-reserve-left">
      <CalendarViewSelect
        ref="calendar"
        v-model="currentDate"
        :legend-items="legendItems"
        :dot-calculator="reserveDotCalculator"
        @month-change="getMonthData"
        @change="handleDayClick"
      />
    </div>

    <div class="room-reserve-right">
      <ContentWrap class="search-wrap">
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="所属园区" prop="schoolCode">
            <el-select
              v-model="queryParams.schoolCode"
              placeholder="请选择所属园区"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SCHOOL_CODE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_MEETING_RESERVE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['school:room-reserve:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>

            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['school:device-gate-card:create']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>

            <!-- <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:room-reserve:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button> -->
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="table-wrap table-list !mb-0">
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <el-table-column label="园区" align="center" prop="schoolCode">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SCHOOL_CODE" :value="scope.row.schoolCode" />
            </template>
          </el-table-column>
          <el-table-column label="功能室" align="center" prop="roomName" />
          <el-table-column label="班级" align="center" prop="className" />
          <el-table-column label="预约人" align="center" prop="userName" />
          <el-table-column
            label="开始时间"
            align="center"
            prop="startTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column
            label="结束时间"
            align="center"
            prop="endTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="使用时长" align="center">
            <template #default="scope"> {{ scope.row.duration }} 分钟 </template>
          </el-table-column>
          <el-table-column
            label="附件"
            align="center"
            prop="fileUrls"
            :show-overflow-tooltip="false"
          >
            <template #default="scope">
              <FileListView :file-list="scope.row.fileUrls" />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SCHOOL_MEETING_RESERVE_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="维护状态" align="center" prop="maintainStatus" min-width="82px">
            <template #default="scope">
              <dict-tag
                :type="DICT_TYPE.SCHOOL_ROOM_MAINTAIN_STATUS"
                :value="scope.row.maintainStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="180px" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:room-reserve:update']"
              >
                编辑
              </el-button>
              <el-button link type="primary" @click="handleMaintain(scope.row)"> 维护 </el-button>
              <el-button
                v-if="0 == scope.row.status"
                link
                type="warning"
                @click="handleCancel(scope.row.id)"
                v-hasPermi="['school:meeting-reserve:update']"
              >
                取消
              </el-button>
              <el-button
                v-if="1 == scope.row.status"
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:room-reserve:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <RoomReserveForm ref="formRef" @success="handleFormSuccess" />

  <!-- 功能室排期导入对话框 -->
  <RoomReserveImport ref="importFormRef" />
  <MaintainForm ref="maintainFormRef" @success="handleFormSuccess" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { RoomReserveApi } from '@/api/school/room/reserve'
import RoomReserveForm from './RoomReserveForm.vue'
import RoomReserveImport from './RoomReserveImport.vue'
import MaintainForm from './MaintainForm.vue'
import { usePageList } from '@/hooks/web/usePageList'
import { LegendItem, CalendarDot } from '@/components/CalendarViewSelect/index.vue'

const route = useRoute()

const importFormRef = ref()

/** 功能室预约 列表 */
defineOptions({ name: 'SchoolRoomReserve' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const calendar = ref() // 日历组件实例
const currentDate: any = ref(new Date()) // 当前选中的日期
const monthData = ref<Record<string, number>>({}) // 月份数据，记录每天的预约数量

// 定义图例项
const legendItems: LegendItem[] = [
  {
    style: { backgroundColor: 'var(--el-color-primary)', width: '6px' },
    text: '单个预约'
  },
  {
    style: { backgroundColor: 'var(--el-color-primary)', width: '12px' },
    text: '多个预约'
  }
]

// 定义预约点计算器
const reserveDotCalculator = (day: string): CalendarDot[] => {
  const key = day.replace(/-/g, '')
  const reserveCount = monthData.value[key] || 0
  const dots: CalendarDot[] = []

  if (reserveCount === 1) {
    // 单个预约
    dots.push({
      style: { backgroundColor: 'var(--el-color-primary)', width: '6px' }
    })
  } else if (reserveCount > 1) {
    // 多个预约，比单个预约宽一倍
    dots.push({
      style: { backgroundColor: 'var(--el-color-primary)', width: '12px' }
    })
  }

  return dots
}

// 使用 usePageList hook 管理分页数据
const { list, total, queryParams, loading, getList } = usePageList({
  toast: message,
  queryFn: RoomReserveApi.getMeetingReserveByDay
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 获取指定月份的预约数据 */
const getMonthData = async (month: string) => {
  try {
    // 获取月份预约数据
    const data = await RoomReserveApi.getMeetingReserveByMonth(month, queryParams.roomType)
    monthData.value = data || {}
  } catch (error) {
    console.error('获取月份预约数据失败:', error)
  }
}

/** 处理日期点击 */
const handleDayClick = (data: any) => {
  const date = new Date(data.day)
  // 更新查询参数中的日期
  queryParams.day = formatDate(date, 'YYYYMMDD')
  // 重新获取数据
  getList(true) // true表示初始化查询
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList(true) // true表示初始化查询
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, queryParams.roomType, id)
}

/** 维护预约 列表 */
const maintainFormRef = ref()

// 打开维护预约表单
const handleMaintain = (row) => {
  maintainFormRef.value.open(row)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RoomReserveApi.deleteRoomReserve(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    // 重新获取当前月份数据以更新日历上的点
    const month = formatDate(currentDate.value, 'YYYYMM')
    await getMonthData(month)
  } catch {}
}

/** 取消按钮操作 */
const handleCancel = async (id: number) => {
  try {
    // 二次确认
    await message.confirm(`确定取消当前预约吗？`)
    // 发起取消
    await RoomReserveApi.cancelRoomReserve(id)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
    // 重新获取当前月份数据以更新日历上的点
    const month = formatDate(currentDate.value, 'YYYYMM')
    await getMonthData(month)
  } catch {}
}

/** 用户功能室排期 */
const handleImport = () => {
  importFormRef.value.open(queryParams.roomType)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RoomReserveApi.exportRoomReserve(queryParams)
    download.excel(data, '功能室预约.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 表单操作成功回调 */
const handleFormSuccess = async () => {
  // 重新获取当前月份数据以更新日历上的点
  const month = formatDate(currentDate.value, 'YYYYMM')
  await getMonthData(month)
  // 刷新列表
  await getList()
}

// 路由到 categoryId 映射关系
const pathToTypeMap = {
  '/school/room/func/room-reserve': '1', //功能室
  '/school/room/game-zone/game-reserve': '2' //游戏区
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(
  () => route.path,
  (path) => {
    // 匹配路径并赋值 resourceCode
    queryParams.roomType = pathToTypeMap[path] || '1'
  },
  {
    immediate: true //立即执行一次
  }
)

/** 初始化 **/
onMounted(() => {
  // 获取当前月份数据
  const month = formatDate(currentDate.value, 'YYYYMM')
  getMonthData(month)
  // 获取当前日期的预约
  handleDayClick({ day: currentDate.value })
})
</script>

<style lang="scss" scoped>
.room-reserve-container {
  display: flex;
  column-gap: 20px;
  height: $content-height;
}

.room-reserve-left {
  width: 350px;
  padding: 15px;
  background-color: #fff;
  flex-shrink: 0;
}

.room-reserve-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .search-wrap,
  .card-wrap {
    background-color: #fff;
  }

  .table-list {
    :deep() {
      .el-card__body {
        height: calc($content-height - 65px);
        overflow-y: hidden;
      }
    }
  }
}
</style>
